/*
 * @(#)ParseWorkflowQueryRecordXML.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.core;

import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.dcivision.workflow.bean.WorkflowQueryRecord;
import com.dcivision.workflow.web.ListWorkflowMonitoringForm;

/**
 * ParseWorkflowQueryRecordXML.java
 *
 * This class is responsible for handling workflow monitoring query.
 *
 * @author Dick Xie
 * @company DCIVision Limited
 * @creation date 31/12/2004
 * @version $Revision: 1.7.10.1 $
 */
public class ParseWorkflowQueryRecordXML {
  
  public static final String REVISION = "$Revision: 1.7.10.1 $";
  
  protected Log log = LogFactory.getLog(this.getClass().getName());
  
  Vector v;
  
  public ParseWorkflowQueryRecordXML() {
  }
  
 /**
  * Parse a XML document and save data into form
  * 
  * @param form The ListWorkflowMonitoringForm object
  * @param request The HttpServletRequest object
  * @param workflowQueryRecord The WorkflowQueryRecord object
  * @see com.dcivision.workflow.web.ListWorkflowMonitoringForm
  */
  public void getParseing(ActionForm form, HttpServletRequest request,
      WorkflowQueryRecord workflowQueryRecord) {
    ListWorkflowMonitoringForm maintForm = (ListWorkflowMonitoringForm) form;
    StringBuffer sb = new StringBuffer();
    sb = (StringBuffer) workflowQueryRecord.getXmlQuery();
    Document doc = null;
    //File file=new
    // File(locMaster.getLocPath()+"/query_"+this.getSessionContainer(request).getUserRecordID.toString+".xml");
    try {
      doc = this.parse(sb);
      this.setFormData(doc, maintForm, request);
      maintForm.setQueryID(workflowQueryRecord.getID().toString());
      maintForm.setQueryName(workflowQueryRecord.getQueryName());
      maintForm.setQueryDescription(workflowQueryRecord.getQueryDescription());
      maintForm.setQueryType(workflowQueryRecord.getQueryType());
    } catch (ParserConfigurationException ex) {
      log.error(ex, ex);
    } catch (IOException ex) {
      log.error(ex, ex);
    } catch (SAXException ex) {
      log.error(ex, ex);
    }
  }
  
  /**
   * Parse the enter string buffer to a xml Document object
   * 
   * @param stringbuffer The StringBuffer object containing the xml
   * @return A Document object
   * @throws SAXException
   * @throws IOException
   * @throws ParserConfigurationException
   */
  public Document parse(StringBuffer sb) throws SAXException, IOException,
  ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    docBuilder.setErrorHandler(new ErrorHandler() {
      
      public void error(SAXParseException e) throws SAXException {
        log.error("A error occured at line " + e.getLineNumber()
            + " Error Message: " + e.getMessage());
      }
      
      public void fatalError(SAXParseException e) throws SAXException {
        log.error("A fatal error occured at line " + e.getLineNumber()
            + " Fatal error Message: " + e.getMessage());
      }
      
      public void warning(SAXParseException e) throws SAXException {
        log.error("A waringing occured at line " + e.getLineNumber()
            + " Warning Message: " + e.getMessage());
      }
    });
    
    StringReader reader = new StringReader(sb.toString());
    InputSource inputSource = new InputSource(reader);
    Document document = docBuilder.parse(inputSource);
    return document;
  }
  
  /**
   * Sets the form data for the saved query
   * 
   * @param doc The saved xml Document object
   * @param maintForm The search form
   * @param request The http request
   */
  protected void setFormData(Document doc,
      ListWorkflowMonitoringForm maintForm, HttpServletRequest request) {
    
    NodeList taskTypeList = doc.getElementsByTagName("taskType");
    if (taskTypeList.getLength() > 0) {
      Element actionTakerNode = (Element) taskTypeList.item(0);
      Node taskTypeN = taskTypeList.item(0).getFirstChild();
      String taskType = "";
      if (taskTypeN != null) {
        taskType = taskTypeN.getNodeValue();
      }
      
      maintForm.setTaskType(taskType);
    }
    NodeList actionTakerList = doc.getElementsByTagName("actionTaker");
    if (actionTakerList.getLength() > 0) {
      Element actionTakerNode = (Element) actionTakerList.item(0);
      Node actionTakerN = actionTakerList.item(0).getFirstChild();
      String actionTaker = "";
      if (actionTakerN != null) {
        actionTaker = actionTakerN.getNodeValue();
      }
      
      maintForm.setActionTaker(actionTaker);
    }
    
    NodeList priorityList = doc.getElementsByTagName("priority");
    if (priorityList.getLength() > 0) {
      Element priorityNode = (Element) priorityList.item(0);
      Node priorityN = priorityList.item(0).getFirstChild();
      String priority = "";
      if (priorityN != null) {
        priority = priorityN.getNodeValue();
      }
      
      maintForm.setPriority(priority);
    }
    
    NodeList queryDateList = doc.getElementsByTagName("Query_date");
    if (queryDateList.getLength() > 0) {
      Element queryDateNode = (Element) queryDateList.item(0);
      
      NodeList queryDateSubList = queryDateNode.getElementsByTagName("from");
      NodeList queryDateToSubList = queryDateNode.getElementsByTagName("to");
      String queryDateFromValue = "";
      String queryDateToValue = "";
      if (queryDateSubList.item(0).getFirstChild() != null) {
        queryDateFromValue = queryDateSubList.item(0).getFirstChild()
        .getNodeValue();
      }
      if (queryDateToSubList.item(0).getFirstChild() != null) {
        queryDateToValue = queryDateToSubList.item(0).getFirstChild()
        .getNodeValue();
      }
      maintForm.setDatePeriodFrom(queryDateFromValue);
      maintForm.setDatePeriodTo(queryDateToValue);
    }
    
    NodeList statusList = doc.getElementsByTagName("status");
    if (statusList.getLength() > 0) {
      Element statusNode = (Element) statusList.item(0);
      Node statusN = statusList.item(0).getFirstChild();
      String status = "";
      if (statusN != null) {
        status = statusN.getNodeValue();
      }
      
      maintForm.setStatus(status);
    }
    NodeList workflowCategoryIDList = doc
    .getElementsByTagName("workflowCategoryID");
    if (workflowCategoryIDList.getLength() > 0) {
      Element workflowCategoryIDNode = (Element) workflowCategoryIDList.item(0);
      Node workflowCategoryIDN = workflowCategoryIDList.item(0).getFirstChild();
      String workflowCategoryID = "";
      if (workflowCategoryIDN != null) {
        workflowCategoryID = workflowCategoryIDN.getNodeValue();
      }
      
      maintForm.setWorkflowCategoryID(workflowCategoryID);
    }
    NodeList submitterList = doc.getElementsByTagName("submitter");
    if (submitterList.getLength() > 0) {
      Element submitterNode = (Element) submitterList.item(0);
      Node submitterN = submitterList.item(0).getFirstChild();
      String submitter = "";
      if (submitterN != null) {
        submitter = submitterN.getNodeValue();
      }
      
      maintForm.setSubmitter(submitter);
    }
    NodeList workflowRecordIDList = doc
    .getElementsByTagName("workflowRecordID");
    if (workflowRecordIDList.getLength() > 0) {
      Element workflowRecordIDNode = (Element) workflowRecordIDList.item(0);
      Node workflowRecordIDN = workflowRecordIDList.item(0).getFirstChild();
      String workflowRecordID = "";
      if (workflowRecordIDN != null) {
        workflowRecordID = workflowRecordIDN.getNodeValue();
      }
      maintForm.setWorkflowRecordID(workflowRecordID);
    }
    NodeList tractIDList = doc.getElementsByTagName("tractID");
    if (tractIDList.getLength() > 0) {
      Element tractIDNode = (Element) tractIDList.item(0);
      Node tractIDN = tractIDList.item(0).getFirstChild();
      String tractID = "";
      if (tractIDN != null) {
        tractID = tractIDN.getNodeValue();
      }
      
      maintForm.setTrackID(tractID);
    }
    NodeList stepNameList = doc.getElementsByTagName("stepName");
    if (stepNameList.getLength() > 0) {
      Element stepNameNode = (Element) stepNameList.item(0);
      Node stepNameN = stepNameList.item(0).getFirstChild();
      String stepName = "";
      if (stepNameN != null) {
        stepName = stepNameN.getNodeValue();
      }
      maintForm.setStepName(stepName);
    }
    
    NodeList stageNameList = doc.getElementsByTagName("stageName");
    if (stageNameList.getLength() > 0) {
      Element stageNameNode = (Element) stageNameList.item(0);
      Node stageNameN = stageNameList.item(0).getFirstChild();
      String stageName = "";
      if (stageNameN != null) {
      	stageName = stageNameN.getNodeValue();
      }
      maintForm.setStageName(stageName);
    }
    
    NodeList relatedObjectList = doc.getElementsByTagName("relatedObject");
    if (relatedObjectList.getLength() > 0) {
      Element relatedObjectNode = (Element) relatedObjectList.item(0);
      Node relatedObjectN = relatedObjectList.item(0).getFirstChild();
      String relatedObject = "";
      if (relatedObjectN != null) {
        relatedObject = relatedObjectN.getNodeValue();
      }
      
      maintForm.setRelatedObject(relatedObject);
    }
    NodeList descriptionList = doc.getElementsByTagName("description");
    if (descriptionList.getLength() > 0) {
      Element descriptionNode = (Element) descriptionList.item(0);
      Node descriptionN = descriptionList.item(0).getFirstChild();
      String description = "";
      if (descriptionN != null) {
        description = descriptionN.getNodeValue();
      }
      
      maintForm.setWorkflowDescription(description);
    }
    NodeList periodTimesList = doc.getElementsByTagName("periodTimes");
    if (periodTimesList.getLength() > 0) {
      Element periodTimesNode = (Element) periodTimesList.item(0);
      Node periodTimesN = periodTimesList.item(0).getFirstChild();
      String periodTimes = "";
      if (periodTimesN != null) {
        periodTimes = periodTimesN.getNodeValue();
      }
      maintForm.setPeriodTimes(periodTimes);
    }
    NodeList periodTypeList = doc.getElementsByTagName("periodType");
    if (periodTypeList.getLength() > 0) {
      Element periodTypeNode = (Element) periodTypeList.item(0);
      Node periodTypeN = periodTypeList.item(0).getFirstChild();
      String periodType = "";
      if (periodTypeN != null) {
        periodType = periodTypeN.getNodeValue();
      }
      
      maintForm.setPeriodType(periodType);
    }
    NodeList periodTimeTypeList = doc.getElementsByTagName("periodTimeType");
    if (periodTimeTypeList.getLength() > 0) {
      Element periodTimeTypeNode = (Element) periodTimeTypeList.item(0);
      Node periodTimeTypeN = periodTimeTypeList.item(0).getFirstChild();
      String periodTimeType = "";
      if (periodTimeTypeN != null) {
        periodTimeType = periodTimeTypeN.getNodeValue();
      }
      
      maintForm.setPeriodTimeType(periodTimeType);
    }
    //added by nancy
    NodeList taskCommentList = doc.getElementsByTagName("taskComment");
    if (taskCommentList.getLength() > 0) {
      Element taskCommentNode = (Element) taskCommentList.item(0);
      Node taskCommentN = taskCommentList.item(0).getFirstChild();
      String taskComment = "";
      if (taskCommentN != null) {
        taskComment = taskCommentN.getNodeValue();
      }
      
      maintForm.setTaskComment(taskComment);
    }
    NodeList attachmentNameList = doc.getElementsByTagName("attachmentName");
    if (attachmentNameList.getLength() > 0) {
      Element attachmentNameNode = (Element) attachmentNameList.item(0);
      Node attachmentNameN = attachmentNameList.item(0).getFirstChild();
      String attachmentName = "";
      if (attachmentNameN != null) {
        attachmentName = attachmentNameN.getNodeValue();
      }
      maintForm.setAttachmentName(attachmentName);
    }
    //end
    
    NodeList workflowGroupIDList = doc.getElementsByTagName("workflowGroupID");
    if (workflowGroupIDList.getLength() > 0) {
      Element workflowGroupIDNode = (Element) workflowGroupIDList.item(0);
      Node workfowGroupIDN = workflowGroupIDList.item(0).getFirstChild();
      String workflowGroupID = "";
      if (workfowGroupIDN != null) {
        workflowGroupID = workfowGroupIDN.getNodeValue();
      }
      maintForm.setWorkflowGroupID(workflowGroupID);
    }
  }
  /**
   * Gets the value of a tag with name tagName in the given elem context
   * 
   * @param tagName The tag name
   * @param elem The Element context
   * @return The tag value
   */
  public String getTagValue(String tagName, Element elem) {
    String s = "";
    Element childNode = (Element) elem.getElementsByTagName(tagName).item(0);
    s = ((Text) childNode.getFirstChild()).getData().trim();
    return s;
  }
  
}